package com.example.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crm.entity.SalesProcess;
import com.example.crm.entity.SalesStage;
import com.example.crm.mapper.SalesStageMapper;
import com.example.crm.service.SalesProcessService;
import com.example.crm.service.SalesStageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 销售阶段服务实现类
 */
@Service
public class SalesStageServiceImpl extends ServiceImpl<SalesStageMapper, SalesStage> implements SalesStageService {

    @Autowired
    @Lazy  // 使用延迟加载解决循环依赖
    private SalesProcessService salesProcessService;

    @Override
    public List<SalesStage> listStagesByProcessId(Long processId) {
        LambdaQueryWrapper<SalesStage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SalesStage::getProcessId, processId)
                    .orderByAsc(SalesStage::getOrderNum);
        
        List<SalesStage> stages = list(queryWrapper);
        
        // 填充流程信息
        if (!stages.isEmpty()) {
            SalesProcess process = salesProcessService.getById(processId);
            stages.forEach(stage -> stage.setProcess(process));
        }
        
        return stages;
    }

    @Override
    public SalesStage getStageDetail(Long id) {
        SalesStage stage = getById(id);
        if (stage != null && stage.getProcessId() != null) {
            SalesProcess process = salesProcessService.getById(stage.getProcessId());
            stage.setProcess(process);
        }
        return stage;
    }

    @Override
    public boolean addStage(SalesStage stage) {
        return save(stage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAddStages(List<SalesStage> stages, Long processId) {
        // 设置流程ID
        stages.forEach(stage -> stage.setProcessId(processId));
        
        // 批量保存
        return saveBatch(stages);
    }

    @Override
    public boolean updateStage(SalesStage stage) {
        return updateById(stage);
    }

    @Override
    public boolean deleteStage(Long id) {
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteStagesByProcessId(Long processId) {
        LambdaQueryWrapper<SalesStage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SalesStage::getProcessId, processId);
        
        return remove(queryWrapper);
    }
} 